import React,{useState} from "react";
import {View,Text,StyleSheet,TextInput,Platform,ScrollView,PermissionsAndroid,Image} from "react-native";
import {windowWidth,windowHeight,getWidth} from "../../utils";
import Touchable from "../../components/Touchable";
import {connect, ConnectedProps} from 'react-redux';
import {RootState} from "@/models/index";
import Toast from 'react-native-root-toast';
import IconFont from '../../assets/iconfont';
import {IUserInfo} from '@/models/user';
import AsyncStorage from '@react-native-async-storage/async-storage';
// import ImagePicker from 'react-native-image-crop-picker';
import  { launchCamera ,  launchImageLibrary }  from  'react-native-image-picker' ;
interface IFormData {
  user_id:string;
  experience:any;
  identity:"摄影师";
}
const mapStateToProps = ({users, loading}: RootState) => {
  return {
    // 在触发getUserInfo方法时加上加载效果
    // loading: loading.effects['users/modifyPassword'],
  };
};
const connector = connect(mapStateToProps);
type ModelState = ConnectedProps<typeof connector>;
interface IProps extends ModelState{
  navigation: {goBack: any, navigate:any};
  route: any;
}
const ToBePhotographer = (props:IProps) => {
  const {route,dispatch,navigation} = props;
  const [formData,setFormData] = useState<IFormData>({
    user_id:route.params.user_id,
    experience:null,
    identity:"摄影师",
  });
  const [images, setImages] = useState<any[]>([]);
  const onChangeText = (text: string, name: string) => {
    console.log('name1111111111111', name, 'text111111111111111111', text);
    let obj = {[name]: text};
    let newFormData = Object.assign(formData, obj);
    console.log("newFormData",newFormData);
    setFormData(newFormData);
  };
  const handleAddPicCheck1 = () => {
    console.warn('添加图片------check');
    const options: any = {
      cameraType: 'back',
      mediaType: 'photo', // 媒体类型还可以是视频或者图片视频二者混合，默认选取一张
      videoQuality: 'high',
      durationLimit: 10,
      maxWidth: 720,
      maxHeight: 1280,
      quality: 1,
      // 允许选择多张
      // multiple: true, // 设置为true，可以选择多张图片
      selectionLimit:0
    };
    async function requestCameraPermission() {
      console.log("Platform.Version",Platform.Version)
      if (Platform.Version as number >= 31) {
        // 如果运行的是 Android 12 或更高版本，选用新模型来请求相机权限
        // const result = await requestPermissionAndroid12('android.permission.CAMERA');
        // 请求本地存储权限
        const result = await requestPermissionAndroid12('android.permission.READ_EXTERNAL_STORAGE')
        if (result === PermissionsAndroid.RESULTS.GRANTED) {
          console.log("加载权限")
          // launchCamera(options, (res)=>{
          //   console.log("res",res)
          // });
          //打开图库
          launchImageLibrary(options, ({assets})=>{
            console.log("res1111111111111111111111",assets)
            // res {"assets": [{"fileName": "rn_image_picker_lib_temp_00144087-1f0f-4d10-ae39-5ad9f2a02440.jpg", "fileSize": 232251, "height": 720, "type": "image/jpeg", "uri": "file:///data/user/0/com.xipai/cache/rn_image_picker_lib_temp_00144087-1f0f-4d10-ae39-5ad9f2a02440.jpg", "width": 720}]}
            if(assets) {
              setImages(assets)
            }
          });
          console.log('Camera permission granted权限通过');
        } else {
          console.log('Camera permission denied权限拒绝');
        }
      } else {
        // 如果运行的是 Android 11 或更低版本，使用之前的版本的权限请求模型来请求
        try {
          const granted = await PermissionsAndroid.request(
            // PermissionsAndroid.PERMISSIONS.CAMERA,
            PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
            {
              title: 'App android.permission.READ_EXTERNAL_STORAGE Permission',
              message: 'App needs access to android.permission.READ_EXTERNAL_STORAGE.',
              buttonNeutral: 'Ask Me Later',
              buttonNegative: 'Cancel',
              buttonPositive: 'OK',
            },
          );
          if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            console.log('Camera permission granted,11一下权限请求通过');
          } else {
            console.log('Camera permission denied,11一下权限请求失败');
          }
        } catch (err) {
          console.warn(err);
        }
      }
    }
    async function requestPermissionAndroid12(permission:any) {
      // 检查是否该应用被永久允许了相机权限android.permission.CAMERA
      const isGranted = await PermissionsAndroid.check(permission);
      if (isGranted) {
        // 如果设置的应用权限管理中用户允许了，直接返回许可令
        return PermissionsAndroid.RESULTS.GRANTED;
      }
      // 询问用户是否给权限，如果用户设置的是每次使用时询问
      const result = await PermissionsAndroid.request(permission);
      if (result === PermissionsAndroid.RESULTS.GRANTED) {
        console.log("yunxu")
        return PermissionsAndroid.RESULTS.GRANTED;
      } else if (result === PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN) {
        throw new Error('Permission denied with never ask again');
      } else {
        throw new Error('Permission denied');
      }
    }
    
   
    requestCameraPermission()
    
  };

  // const handleAddPicCheck = () => {
  //   ImagePicker.openPicker({
  //     // width: 300,
  //     // height: 400,
  //     // cropping: true
  //     multiple: true
  //   }).then(image => {
  //     console.log("拿到了image",image);
  //   });
  // }
  const handleCompeleteInfo = () => {
    console.log("handleCompeleteInfo");
    console.log("完善摄影师身份数据",formData);
    let reg = /^\d+$/;
    if (!reg.test(formData.experience)) {
      Toast.show('摄影年限必须为数字', {
        position: Toast.positions.CENTER,
        duration: Toast.durations.LONG,
        shadow: true,
        animation: true,
      });
      return;
    }
    if (JSON.stringify(images) === "[]") {
      Toast.show('注册成为摄影师必须上传摄影作品', {
        position: Toast.positions.CENTER,
        duration: Toast.durations.LONG,
        shadow: true,
        animation: true,
      });
      return;
    }

    // 此处应该还有摄影师定位需要被获取--略过
    let newFormData = JSON.parse(JSON.stringify(formData));
    newFormData.images = images;
    dispatch({
      type: 'users/compeleteInfo',
      payload: {
        formData: newFormData,
        callback: () => {
          // 更新本地的currentUserInfo
          dispatch({
            type: 'users/getCurrentUser',
            payload: {
              user_id: route.params.user_id,
              callback: (data: IUserInfo[]) => {
                console.log('完善摄影师身份页面拿到了data', data);
                data[0] &&
                  AsyncStorage.setItem(
                    'currentUserInfo',
                    JSON.stringify(data[0]),
                  );
                Toast.show('完善身份信息成功', {
                  position: Toast.positions.CENTER,
                  duration: Toast.durations.LONG,
                  shadow: true,
                  animation: true,
                });
                navigation.goBack();
              },
            },
          });
        },
      },
    });

  }
  return (
    <View style={styles.toBePhotographer}>
     <ScrollView>
     <View style={styles.mainBox}>
        <Text style={styles.title}>完善摄影师身份信息</Text>
           <TextInput
          placeholder="请输入摄影年限"
          style={[styles.inputBox, styles.inputBoxTop]}
          onChangeText={text => onChangeText(text, 'experience')}></TextInput>
        <Touchable style={styles.avatarBox} onPress={handleAddPicCheck1}>
          {JSON.stringify(images) === '[]' && (
            <IconFont name="icon-jia" size={30} color={'#A75E5E'}></IconFont>
          )}
          {JSON.stringify(images) === '[]' && (
            <Text style={styles.avatar}>请上传摄影作品</Text>
          )}
          {JSON.stringify(images) !== '[]' && (
            <View style={styles.selectImageBox}>
              <Text style={styles.text}>摄影作品</Text>
              <View style={styles.imageBox}>
              {images.map(i => {
                return (
                  <Image source={{uri: i.uri}} style={styles.avatarImage} />
                );
              })}
            </View>
            </View>
          )}
        </Touchable>
       
        <Touchable onPress={handleCompeleteInfo} style={styles.loginBtnBox}>
          <Text style={styles.loginBtn}>完善摄影师信息</Text>
        </Touchable>
      </View>
     </ScrollView>
    </View>
  );
}
const styles = StyleSheet.create({
  toBePhotographer:{
    padding: 10,
    backgroundColor: '#fff',
    width: windowWidth,
    height: windowHeight,
  },
  mainBox: {
    marginTop:70,
    display:"flex",
    alignItems:"center",
    
  },
  bigTitle: {
    fontSize:70,
    fontWeight:"700",
    color:"#A75E5E",
  },
  title: {
    fontSize:16,
    fontWeight:"700",
    fontFamily:"Edwardian Script ITC",
    color:"#A75E5E",
  },
  image: {
    width:200,
    height:130,
    resizeMode: 'stretch',
    marginBottom:10,
  },
  image1: {
    width:150,
    height:16,
    resizeMode: 'stretch',
  },
  image2:{
    width:240,
    height:18,
    resizeMode: 'stretch',
  },
  inputBox: {
    width:getWidth(80),
    height:40,
    borderBottomColor:"#A75E5E",
    borderBottomWidth:1,
  },
  inputBoxTop: {
    marginTop:20
  },
  loginBtnBox:{
    height:150
  },
  loginBtn:{
    width:getWidth(50),
    height:35,
    color:"#fff",
    textAlign:"center",
    backgroundColor:"#A75E5E",
    marginVertical:35,
    borderRadius:35,
    lineHeight:35
  },
  avatarBox: {
    width: windowWidth,
    // height:50,
    padding: 15,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
  },
  avatar: {
    color: '#999',
  },
  selectImageBox:{
    width:"100%",
  },
  imageBox:{
    width:"100%",
    display:"flex",
    flexDirection:"row",
    flexWrap:"wrap"
  },
  avatarImage: {
    width:103,
    height:103,
    margin:3,
  },
  text:{
    paddingLeft:10,
    paddingBottom:10
  }
})
export default connector(ToBePhotographer);
